package me.exchange.com.modules.system.service.impl;


import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import com.amazonaws.util.Md5Utils;
import me.exchange.com.modules.system.domain.FileContent;
import me.exchange.com.modules.system.domain.Scroll;
import me.exchange.com.modules.system.domain.User;
import me.exchange.com.modules.system.dto.ScrollDto;
import me.exchange.com.modules.system.dto.ScrollQueryCriteria;
import me.exchange.com.modules.system.mapper.ScrollerMapper;
import me.exchange.com.modules.system.repository.ScrollerRepository;
import me.exchange.com.modules.system.repository.UserRepository;
import me.exchange.com.modules.system.service.ScrollService;
import me.exchange.com.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;

import java.awt.print.Pageable;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author zhaojing
 * @create2020/5/23
 */
@Service
@CacheConfig(cacheNames = "scroll")
@Transactional(propagation = Propagation.SUPPORTS,readOnly = true,rollbackFor = Exception.class)
public class ScrollServiceImpl implements ScrollService {

    @Autowired
    private ScrollerMapper scrollerMapper;
    
    @Autowired
    private ScrollerRepository scrollerRepository;

    @Autowired
    private UserRepository userRepository;
    
    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    @Cacheable(key = "#p0")
    public ScrollDto findById(Long id) {
     
     Scroll scroll = scrollerRepository.findById(id).orElseGet(Scroll::new);
     
     ValidationUtil.isNull(scroll.getId(),"Scroll","id",id);
     
     return scrollerMapper.toDto(scroll);
    }

 /**
  * 创建
  * @param resources
  * @return
  */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public ScrollDto create(Scroll resources) {

     User user = userRepository.findByUsername(SecurityUtils.getUsername());

     resources.setCAdminId(user.getId());

     resources.setCAdminTime(new Timestamp(System.currentTimeMillis()));

     resources.setIsdel(true);

     return scrollerMapper.toDto(scrollerRepository.save(resources));
    }

    /**
     * 编辑
     * @param resources
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(Scroll resources) {
        User user = userRepository.findByUsername(SecurityUtils.getUsername());

        Scroll scroll = scrollerRepository.findById(resources.getId()).orElseGet(Scroll::new);

        ValidationUtil.isNull(scroll.getId(),"Scroll","id",resources.getId());

        scroll.copy(resources);

        scroll.setUAdminId(user.getId());

        scroll.setUAdminTime(new Timestamp(System.currentTimeMillis()));

        scrollerRepository.save(scroll);
    }

    /**
     * 删除数据
     * @param id
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {

        User user = userRepository.findByUsername(SecurityUtils.getUsername());

        Scroll scroll = scrollerRepository.findById(id).orElseGet(Scroll::new);

        scroll.setIsdel(false);

        scroll.setUAdminTime(new Timestamp(System.currentTimeMillis()));

        scroll.setUAdminId(user.getId());

        scrollerRepository.save(scroll);

    }

    /**
     * 多选删除
     * @param ids
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Set<Long> ids) {

        User user = userRepository.findByUsername(SecurityUtils.getUsername());

        for (Long id : ids) {
            Scroll scroll = scrollerRepository.findById(id).orElseGet(Scroll::new);

            scroll.setIsdel(false);

            scroll.setUAdminTime(new Timestamp(System.currentTimeMillis()));

            scroll.setUAdminId(user.getId());

            scrollerRepository.save(scroll);
        }
    }

    /**
     * 导出数据
     * @param all
     * @param response
     * @throws Exception
     */
    @Override
    public void downLoad(List<ScrollDto> all, HttpServletResponse response) throws Exception {

        List<Map<String,Object>> list = new ArrayList<>();

        for (ScrollDto scroll: all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("名称",scroll.getScrollName());
            map.put("描述",scroll.getRepresent());
            map.put("地址",scroll.getAdress());
            map.put("上线时间",scroll.getOnTime());
            map.put("下线时间",scroll.getOffTime());
            map.put("状态 0未开启 1开启",scroll.getEnabled());
            map.put("创建人",scroll.getCAdminId());
            map.put("创建时间",scroll.getCAdminTime());
            map.put("修改人",scroll.getUAdminId());
            map.put("修改时间",scroll.getUAdminTime());
            map.put("排序",scroll.getSort());
            map.put("上传",scroll.getUpload());
            map.put("是否删除 0未删除 1删除",scroll.getIsdel());
            list.add(map);
        }

        FileUtil.downloadExcel(list,response);

    }

    /**
     * 详情查询
     * @param criteria
     * @return
     */
    @Override
    public List<ScrollDto> queryAll(ScrollQueryCriteria criteria) {

        Sort sort = criteria.getSort();

        return scrollerMapper.toDto(scrollerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteriaQuery, criteriaBuilder),sort));
    }

    /**
     * 分页查询
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public Map<String, Object> queryAll(ScrollQueryCriteria criteria, Pageable pageable) {
        Page<Scroll> page = scrollerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteriaQuery, criteriaBuilder), (org.springframework.data.domain.Pageable) pageable);
        return PageUtil.toPage(page.map(scrollerMapper::toDto));
    }

    /**
     * 修改状态
     * @param criteria
     */
    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void updateEnable(ScrollQueryCriteria criteria) {
        User user = userRepository.findByUsername(SecurityUtils.getUsername());
        Scroll scroll = scrollerRepository.findById(criteria.getId()).orElseGet(Scroll::new);

        ValidationUtil.isNull(scroll.getId(),"Scroll","id",criteria.getId());

        scroll.setUAdminId(user.getId());
        scroll.setUAdminTime(new Timestamp(System.currentTimeMillis()));
        scroll.setId(criteria.getId());
        scroll.setEnabled(criteria.getEnabled());

        scrollerRepository.save(scroll);

    }



}
